package mt.demo.web.comm.resolverArg;

import org.json.JSONArray;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

/**
 * Created by watson on 2015/12/24.
 * 解析json数组
 */
public class ResolverArrayArg implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterAnnotation(WatArrayParam.class) != null;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        String paraName = methodParameter.getParameterName();
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);

        String paraValue = request.getParameter(paraName);
        if (paraValue == null) {
            return null;
        }
        JSONArray array = new JSONArray(paraValue);
        if (array.length() > 0) {
            String listType = (String) array.get(0);

            if (listType.equals("string")) {
                ArrayList<String> strList = new ArrayList<String>();
                for (int i = 1; i < array.length(); i++) {
                    try {
                        strList.add((String) array.get(i));
                    } catch (Exception e) {
                        return null;
                    }
                }
                return strList;
            } else if (listType.equals("int")) {
                ArrayList<Integer> strList = new ArrayList<Integer>();
                for (int i = 1; i < array.length(); i++) {
                    try {
                        strList.add(Integer.parseInt(array.get(i) + ""));
                    } catch (Exception e) {
                        return null;
                    }
                }
                return strList;
            }
        }
        return null;
    }
}
